package mysql

import (
	"MyWeb/internal/config"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var (
	mysqlErr error
)

func InitMysqlDb(cfg *config.Configuration, DbPoint **gorm.DB) error {
	var Db *gorm.DB
	//dsn := "root:ccebdcxy@tcp(127.0.0.1:3306)/shorturl?charset=utf8&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		cfg.Database.DbUser,
		cfg.Database.DbPassword,
		cfg.Database.DbHost,
		cfg.Database.DbPort,
		cfg.Database.DbName,
	)

	Db, mysqlErr = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if mysqlErr != nil {
		return errors.New("The path(dsn) is incorrect ")
	}

	sqlDb, err := Db.DB()
	if err != nil {
		return errors.New("Pooled object acquistion failed ")
	}

	err = sqlDb.Ping()
	if err != nil {
		return errors.New("Pooled database ping failed ")
	}
	//Db.AutoMigrate(&models.UrlMap{})
	sqlDb.SetMaxIdleConns(cfg.Database.MaxIdleConnections)
	sqlDb.SetMaxOpenConns(cfg.Database.MaxOpenConnections)
	sqlDb.SetConnMaxLifetime(time.Hour)
	*DbPoint = Db
	return nil
}
